<template>
  <div class="product-management">
    <PageLayout>
      <!-- 搜索区域 -->
      <template #search>
        <n-card class="search-card">
          <n-form inline :model="searchForm" label-placement="left">
            <n-form-item label="商品名称">
              <n-input v-model:value="searchForm.productName" placeholder="请输入商品名称" clearable />
            </n-form-item>
            <n-form-item label="商品分类">
              <n-select v-model:value="searchForm.category" placeholder="请选择分类" :options="categoryOptions" clearable />
            </n-form-item>
            <n-form-item label="商品状态">
              <n-select v-model:value="searchForm.status" placeholder="请选择状态" :options="statusOptions" clearable />
            </n-form-item>
            <n-form-item>
              <n-button type="primary" @click="handleSearch">
                <template #icon>
                  <n-icon>
                    <SearchOutline />
                  </n-icon>
                </template>
                搜索123
              </n-button>
              <n-button @click="handleReset" style="margin-left: 8px">
                <template #icon>
                  <n-icon>
                    <RefreshOutline />
                  </n-icon>
                </template>
                重置
              </n-button>
            </n-form-item>
          </n-form>
        </n-card>
      </template>

      <!-- 表格头部 -->
      <template #header>
        <div class="table-header-content">
          <!-- <span class="table-title">商品列表</span> -->
          <n-space>
            <n-button type="primary" @click="handleAdd">
              <template #icon>
                <n-icon>
                  <AddOutline />
                </n-icon>
              </template>
              新增商品
            </n-button>
            <n-button @click="handleExport">
              <template #icon>
                <n-icon>
                  <DownloadOutline />
                </n-icon>
              </template>
              导出数据
            </n-button>
          </n-space>
        </div>
      </template>

      <!-- 表格内容 -->
      <template #table>
        <n-data-table :columns="columns" :data="currentPageData" :loading="loading" :single-line="false"
          :scroll-x="1330" :max-height="600" class="data-table" striped />
      </template>

      <!-- 分页 -->
      <template #pagination>
        <n-pagination v-model:page="pagination.page" v-model:page-size="pagination.pageSize"
          :item-count="pagination.itemCount" :page-sizes="[10, 20, 50, 100]" show-size-picker show-quick-jumper
          :prefix="paginationPrefix" @update:page="handlePageChange" @update:page-size="handlePageSizeChange" />
      </template>
    </PageLayout>

    <!-- 新增/编辑产品弹窗 -->
    <n-modal v-model:show="showProductModal" :mask-closable="false" preset="dialog" :title="modalTitle"
      style="width: 700px;">
      <template #default>
        <n-form ref="productFormRef" :model="productForm" :rules="productFormRules" label-placement="left"
          label-width="auto" require-mark-placement="right-hanging">
          <n-form-item label="商品名称" path="productName">
            <n-input v-model:value="productForm.productName" placeholder="请输入商品名称" :disabled="modalMode === 'view'" />
          </n-form-item>
          <n-form-item label="商品分类" path="category">
            <n-select v-model:value="productForm.category" placeholder="请选择商品分类" :options="categoryOptions"
              :disabled="modalMode === 'view'" />
          </n-form-item>
          <n-form-item label="商品价格" path="price">
            <n-input-number v-model:value="productForm.price" placeholder="请输入商品价格" :min="0" :precision="2"
              :disabled="modalMode === 'view'">
              <template #prefix>¥</template>
            </n-input-number>
          </n-form-item>
          <n-form-item label="库存数量" path="stock">
            <n-input-number v-model:value="productForm.stock" placeholder="请输入库存数量" :min="0"
              :disabled="modalMode === 'view'" />
          </n-form-item>
          <n-form-item label="商品状态" path="status">
            <n-select v-model:value="productForm.status" placeholder="请选择商品状态" :options="statusOptions"
              :disabled="modalMode === 'view'" />
          </n-form-item>
          <n-form-item label="商品描述" path="description">
            <n-input v-model:value="productForm.description" type="textarea" placeholder="请输入商品描述" :rows="3"
              :disabled="modalMode === 'view'" />
          </n-form-item>
        </n-form>
      </template>
      <template #action>
        <n-space v-if="modalMode !== 'view'">
          <n-button @click="cancelProductModal">取消</n-button>
          <n-button type="primary" @click="confirmProductModal" :loading="submitLoading">
            {{ modalMode === 'add' ? '新增' : '保存' }}
          </n-button>
        </n-space>
        <n-space v-else>
          <n-button @click="cancelProductModal">关闭</n-button>
          <n-button type="primary" @click="switchToEditMode">编辑</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, h } from 'vue'
import { useMessage, useDialog, FormInst, FormRules } from 'naive-ui'
import { NButton, NTag, NImage } from 'naive-ui'
import {
  SearchOutline,
  RefreshOutline,
  AddOutline,
  DownloadOutline,
  CreateOutline,
  TrashOutline,
  EyeOutline
} from '@vicons/ionicons5'
import PageLayout from '@/components/PageLayout.vue'

// 添加组件名称
defineOptions({
  name: 'ProductManagement-copy'
})

const message = useMessage()
const dialog = useDialog()
const loading = ref(false)

// 弹窗相关
const showProductModal = ref(false)
const modalMode = ref<'add' | 'edit' | 'view'>('add')
const modalTitle = computed(() => {
  const titles = {
    add: '新增商品',
    edit: '编辑商品',
    view: '查看商品'
  }
  return titles[modalMode.value]
})
const submitLoading = ref(false)
const productFormRef = ref<FormInst | null>(null)

// 商品表单
const productForm = ref({
  id: null as number | null,
  productName: '',
  category: 'electronics',
  price: 0,
  stock: 0,
  status: 'active',
  description: '',
  image: '',
  sales: 0,
  createTime: ''
})

// 表单验证规则
const productFormRules: FormRules = {
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '商品名称长度在2到50个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { validator: (rule: any, value: number) => value > 0, message: '价格必须大于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { validator: (rule: any, value: number) => value >= 0, message: '库存不能小于0', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择商品状态', trigger: 'change' }
  ]
}

// 搜索表单
const searchForm = ref({
  productName: '',
  category: null,
  status: null
})

// 分类选项
const categoryOptions = [
  { label: '电子产品', value: 'electronics' },
  { label: '服装配饰', value: 'fashion' },
  { label: '家居用品', value: 'home' },
  { label: '运动户外', value: 'sports' },
  { label: '美妆护肤', value: 'beauty' },
  { label: '食品饮料', value: 'food' }
]

// 状态选项
const statusOptions = [
  { label: '在售', value: 'active' },
  { label: '下架', value: 'inactive' },
  { label: '缺货', value: 'out_of_stock' }
]

// 分页配置
const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 100
})

// 分页前缀
const paginationPrefix = ({ itemCount }: any) => `共 ${itemCount} 条数据`

// 表格列配置
const columns: any[] = [
  {
    title: '商品图片',
    key: 'image',
    width: 100,
    align: 'center',
    render: (row: any) => {
      return h(NImage, {
        width: 60,
        height: 60,
        src: row.image,
        fallbackSrc: 'https://picsum.photos/60/60?random=product',
        objectFit: 'cover',
        style: { borderRadius: '8px' }
      })
    }
  },
  {
    title: '商品名称',
    key: 'productName',
    width: 200,
    fixed: 'left',
    filterable: true,
    render: (row: any) => h('span', {
      style: { fontWeight: '600', color: '#1890ff' }
    }, row.productName)
  },
  {
    title: '商品分类',
    key: 'category',
    width: 120,
    render: (row: any) => {
      const categoryMap: Record<string, string> = {
        electronics: '电子产品',
        fashion: '服装配饰',
        home: '家居用品',
        sports: '运动户外',
        beauty: '美妆护肤',
        food: '食品饮料'
      }
      return categoryMap[row.category] || row.category
    },
    filterable: true,
    filterOptions: categoryOptions.map(item => ({
      label: item.label,
      value: item.value
    })),
    filter: (value: any, row: any) => row.category === value
  },
  {
    title: '商品价格',
    key: 'price',
    width: 120,
    align: 'right',
    render: (row: any) => h('span', {
      style: { fontWeight: '600', color: '#fa541c' }
    }, `¥${row.price.toFixed(2)}`),
    sorter: (row1: any, row2: any) => row1.price - row2.price,
    filterable: true,
    filterOptions: [
      { label: '低价格(<100)', value: 'low' },
      { label: '中等价格(100-1000)', value: 'medium' },
      { label: '高价格(≥1000)', value: 'high' }
    ],
    filter: (value: any, row: any) => {
      if (value === 'low') return row.price < 100
      if (value === 'medium') return row.price >= 100 && row.price < 1000
      if (value === 'high') return row.price >= 1000
      return true
    }
  },
  {
    title: '库存数量',
    key: 'stock',
    width: 100,
    align: 'center',
    render: (row: any) => {
      const color = row.stock > 50 ? 'success' : row.stock > 10 ? 'warning' : 'error'
      return h(NTag, {
        type: color as any,
        size: 'small',
        style: {
          background: color === 'success' ? '#f6ffed' : color === 'warning' ? '#fffbe6' : '#fff2f0',
          color: color === 'success' ? '#52c41a' : color === 'warning' ? '#fa8c16' : '#f5222d',
          border: `1px solid ${color === 'success' ? '#b7eb8f' : color === 'warning' ? '#ffd591' : '#ffccc7'}`
        }
      }, { default: () => row.stock })
    },
    sorter: (row1: any, row2: any) => row1.stock - row2.stock,
    filterable: true,
    filterOptions: [
      { label: '库存不足(<20)', value: 'low' },
      { label: '库存适中(20-50)', value: 'medium' },
      { label: '库存充足(≥50)', value: 'high' }
    ],
    filter: (value: any, row: any) => {
      if (value === 'low') return row.stock < 20
      if (value === 'medium') return row.stock >= 20 && row.stock < 50
      if (value === 'high') return row.stock >= 50
      return true
    }
  },
  {
    title: '已售数量',
    key: 'sales',
    width: 100,
    align: 'center',
    sorter: (row1: any, row2: any) => row1.sales - row2.sales,
    filterable: true,
    filterOptions: [
      { label: '销量较低(<100)', value: 'low' },
      { label: '销量一般(100-300)', value: 'medium' },
      { label: '销量较高(≥300)', value: 'high' }
    ],
    filter: (value: any, row: any) => {
      if (value === 'low') return row.sales < 100
      if (value === 'medium') return row.sales >= 100 && row.sales < 300
      if (value === 'high') return row.sales >= 300
      return true
    }
  },
  {
    title: '商品状态',
    key: 'status',
    width: 100,
    align: 'center',
    render: (row: any) => {
      const statusMap: Record<string, { type: string; label: string }> = {
        active: { type: 'success', label: '在售' },
        inactive: { type: 'error', label: '下架' },
        out_of_stock: { type: 'warning', label: '缺货' }
      }
      const status = statusMap[row.status]
      return h(NTag, { type: status.type as any, size: 'small', round: true }, { default: () => status.label })
    },
    filterable: true,
    filterOptions: statusOptions.map(item => ({
      label: item.label,
      value: item.value
    })),
    filter: (value: any, row: any) => row.status === value
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 200,
    render: (row: any) => h('div', { class: 'time-cell' }, [
      h('div', { class: 'time-date' }, row.createTimeDisplay?.split(' ')[0] || '未知日期'),
      h('div', { class: 'time-time' }, row.createTimeDisplay?.split(' ')[1] || '未知时间')
    ]),
    sorter: (row1: any, row2: any) => row1.createTimeStamp - row2.createTimeStamp
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'center',
    fixed: 'right',
    render: (row: any) => {
      return h('div', { class: 'action-buttons' }, [
        h(NButton, {
          size: 'small',
          type: 'info',
          quaternary: true,
          onClick: () => handleView(row)
        }, { default: () => '查看' }),
        h(NButton, {
          size: 'small',
          type: 'info',
          quaternary: true,
          style: { marginLeft: '8px' },
          onClick: () => handleEdit(row)
        }, { default: () => '编辑' }),
        h(NButton, {
          size: 'small',
          type: 'error',
          quaternary: true,
          style: { marginLeft: '8px' },
          onClick: () => handleDelete(row)
        }, { default: () => '删除' })
      ])
    }
  }
]

// 表格数据
const tableData = ref<any[]>([])
const allData = ref<any[]>([])

// 当前页数据
const currentPageData = computed(() => {
  const start = (pagination.value.page - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return allData.value.slice(start, end)
})

// 生成测试数据
const generateTestData = () => {
  const productNames = ['iPhone 15 Pro', 'MacBook Air M2', 'iPad Pro', '华为Mate 60', '小米14 Pro', 'OPPO Find X7', 'vivo X100', '三星Galaxy S24 Ultra']
  const categories = ['electronics', 'fashion', 'home', 'sports', 'beauty', 'food']
  const statuses = ['active', 'inactive', 'out_of_stock']

  const data = []
  for (let i = 1; i <= 100; i++) {
    const price = Math.floor(Math.random() * 10000) + 100
    const stock = Math.floor(Math.random() * 1000) + 10
    const createTimeStamp = Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000
    const createDate = new Date(createTimeStamp)

    data.push({
      id: i,
      productName: `${productNames[Math.floor(Math.random() * productNames.length)]} ${i}`,
      category: categories[Math.floor(Math.random() * categories.length)],
      price: price,
      stock: stock,
      sales: Math.floor(Math.random() * 500),
      status: statuses[Math.floor(Math.random() * statuses.length)],
      image: `https://picsum.photos/200/200?random=${i}`,
      createTimeStamp: createTimeStamp,
      createTimeDisplay: createDate.toLocaleDateString() + ' ' + createDate.toLocaleTimeString().slice(0, 5),
      createTime: createDate.toLocaleDateString()
    })
  }
  return data
}

// 弹窗处理函数
const openProductModal = (mode: 'add' | 'edit' | 'view', row?: any) => {
  modalMode.value = mode
  if (mode === 'add') {
    productForm.value = {
      id: null,
      productName: '',
      category: 'electronics',
      price: 0,
      stock: 0,
      status: 'active',
      description: '',
      image: '',
      sales: 0,
      createTime: ''
    }
  } else if (row) {
    productForm.value = { ...row }
  }
  showProductModal.value = true
}

const cancelProductModal = () => {
  showProductModal.value = false
  productFormRef.value?.restoreValidation()
}

const confirmProductModal = async () => {
  try {
    await productFormRef.value?.validate()
    submitLoading.value = true

    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000))

    if (modalMode.value === 'add') {
      const newId = Math.max(...allData.value.map((item: any) => item.id)) + 1
      const newProduct = {
        ...productForm.value,
        id: newId,
        createTime: new Date().toLocaleDateString(),
        image: `https://picsum.photos/200/200?random=${newId}`
      }
      allData.value.unshift(newProduct)
      pagination.value.itemCount = allData.value.length
      message.success('商品添加成功')
    } else if (modalMode.value === 'edit') {
      const index = allData.value.findIndex((item: any) => item.id === productForm.value.id)
      if (index !== -1) {
        allData.value[index] = { ...productForm.value }
        message.success('商品更新成功')
      }
    }

    submitLoading.value = false
    showProductModal.value = false
  } catch (error) {
    submitLoading.value = false
    console.error('表单验证失败:', error)
  }
}

const switchToEditMode = () => {
  modalMode.value = 'edit'
}

// 事件处理
const handleSearch = () => {
  loading.value = true
  setTimeout(() => {
    message.success('搜索完成')
    loading.value = false
  }, 1000)
}

const handleReset = () => {
  searchForm.value = {
    productName: '',
    category: null,
    status: null
  }
  message.info('已重置搜索条件')
}

const handleAdd = () => {
  openProductModal('add')
}

const handleExport = () => {
  message.info('导出数据功能')
}

const handleView = (row: any) => {
  openProductModal('view', row)
}

const handleEdit = (row: any) => {
  openProductModal('edit', row)
}

const handleDelete = (row: any) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除商品 "${row.productName}" 吗？此操作不可恢复。`,
    positiveText: '确定删除',
    negativeText: '取消',
    onPositiveClick: () => {
      const index = allData.value.findIndex((item: any) => item.id === row.id)
      if (index !== -1) {
        allData.value.splice(index, 1)
        pagination.value.itemCount = allData.value.length
        message.success('商品删除成功')
      }
    }
  })
}

const handlePageChange = (page: number) => {
  pagination.value.page = page
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize
  pagination.value.page = 1
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
}

onMounted(() => {
  allData.value = generateTestData()
  pagination.value.itemCount = allData.value.length
})
</script>

<style scoped>
.page-container {
  padding: var(--spacing-lg);
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--bg-color-secondary);
}

.search-card {
  flex-shrink: 0;
  margin-bottom: var(--spacing-lg);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-sm);
}

.table-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-header-section {
  flex-shrink: 0;
  background: var(--bg-color-primary);
  border: 1px solid var(--border-color-primary);
  border-bottom: none;
  border-radius: 12px 12px 0 0;
  padding: 16px 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color-primary);
}

.table-content {
  flex: 1;
  overflow: hidden;
  border-left: 1px solid var(--border-color-primary);
  border-right: 1px solid var(--border-color-primary);
  background: var(--bg-color-primary);
}

.table-data-area {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  height: 100%;
  padding-bottom: 65px;
}

.data-table {
  height: auto;
  min-height: 100%;
}

/* 🔧 表格基础样式 - 专业级滚动配置 */
.data-table {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

/* 表格包装器 - 核心滚动配置 */
.data-table :deep(.n-data-table-wrapper) {
  border-radius: 8px;
}

/* 表格基础容器 */
.data-table :deep(.n-data-table) {
  /* 让Naive UI处理所有滚动逻辑 */
}

/* 表头样式 - 确保固定功能正常 */
.data-table :deep(.n-data-table-th) {
  background-color: #fafafa !important;
  font-weight: 600;
  font-size: 14px;
  color: #262626;
  border-bottom: 2px solid #e8e8e8;
  padding: 16px 12px;
  white-space: nowrap;
  position: sticky;
  top: 0;
  z-index: 10;
}

/* 表格单元格样式 */
.data-table :deep(.n-data-table-td) {
  padding: 12px;
  font-size: 14px;
  line-height: 1.5;
  border-bottom: 1px solid #f0f0f0;
  vertical-align: top;
}

/* 表格行悬停效果 */
.data-table :deep(.n-data-table-tr:hover .n-data-table-td) {
  background-color: #f8f9ff !important;
}

/* 时间显示样式 */
.time-cell {
  line-height: 1.4;
}

.time-date {
  font-weight: 500;
  font-size: 13px;
  color: #262626;
  margin-bottom: 2px;
}

.time-time {
  font-size: 12px;
  color: #8c8c8c;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.action-buttons .n-button {
  min-width: 50px;
  height: 28px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.action-buttons .n-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 深色模式适配 */
html.dark .data-table :deep(.n-data-table-th) {
  background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
  color: #ecf0f1;
}

.pagination-section {
  flex-shrink: 0;
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  background: var(--bg-color-primary);
  border: 1px solid var(--border-color-primary);
  border-top: none;
  border-radius: 0 0 12px 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: var(--spacing-md);
  }

  .table-header {
    flex-direction: column;
    gap: var(--spacing-md);
    align-items: stretch;
  }
}
</style>